﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug
{
    public partial class Flash_gen : Form
    {
        //frmMain MainForm = null;
        //public Flash_gen(frmMain Frm)
        //{
        //MainForm = Frm;
        //    InitializeComponent();
        //}

        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke 
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过
        private byte[] Send_buf = new byte[1];
        private byte[] Rec_tmp = new byte[1];

        Int32 flash_end = 0;
        Int32 flash_start = 0;
        int IC_FLASH_TYPE = 0;
        Int32 flash_address_get = 0;
        UInt16 FLAG_OK = 0x00;
        UInt16 ERROR_0 = 0x01;
        byte MipiCommandModeSelect_Flag = 0;

        CRC16 CRCData = new CRC16();
        //frmMain frmTop = null;

        #region 窗体ID
        // 监听挂载
        frmMain frmHelp = null;
        public struct Flash_gen_in //接收区
        {
            public byte ID; //下位机识别ID
        }
        public Flash_gen_in Flash_gen_info = new Flash_gen_in();   //数据

        public Flash_gen(frmMain Flash_gen)
        {
            frmHelp = Flash_gen;
            InitializeComponent();
            frmHelp.Child_window_hide_already = true;
            frmHelp.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体    
            Flash_gen_info.ID = 0x99;   //数据
        }
        //Flash_gen 监听卸载
        private void Flash_gen_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(Flash_gen_DataReceived);
            frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
            frmHelp.Child_window_hide_already = false;
            frmHelp.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Flash_gen_FormClosed！\r\n";
            frmHelp.IC_comboBox.Enabled = true;

        }

        private void Flash_gen_Gamma_VisibleChanged(object sender, EventArgs e)
        {
            if (frmHelp.Child_Gamma_Window_Open_Enable == true) //子窗体已开启标识
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(Flash_gen_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Flash_gen_FormHide！\r\n";
                frmHelp.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(Flash_gen_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Flash_gen_FormOpened！\r\n";
                frmHelp.Child_window_hide_already = false; //子窗体已开启标识
            }
        }
        #endregion

        #region 串口接收
        //串口接收
        private void Flash_gen_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            if (IClosing)
            { return; }
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmHelp.comPort.BytesToRead;
                byte[] buf = new byte[n];
                //byte data;
                Setting.TempRecord.cmdLen = n;
                frmHelp.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    //RECEIVE
                    // 0x0A: 模组Timing参数 设置  返回
                    // 0x0D: 模组的SSD2828配置数据、DriverIC初始化数据  设置  返回
                    // 0x2F: Demura操作    设置  返回
                    // 0x99: 通用读写、寄存器读写  设置  返回
                    // 0x9E: 功耗测试单元  设置  返回
                    if ((buffer[0] == 0x99) && (Setting.TempRecord.cmdLen > 0))
                    {

                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }
                    else if ((buffer[0] == 0x6B) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);
                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }

                    }
                    else if (((buffer[0] == 0x1D) || (buffer[0] == 0x0D) || (buffer[0] == 0x0A) || (buffer[0] == 0x2F) || (buffer[0] == 0x96) || (buffer[0] == 0x99) || (buffer[0] == 0x9e) || (buffer[0] == 0x9f)) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }

                    else
                        buffer.RemoveRange(0, buffer.Count);
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        frmHelp.T1.Enabled = false; //停止超时计数
                                                    //if (Rec_tmp[0] == 0x55)
                                                    //{
                                                    //    switch (Rec_tmp[3])
                                                    //    {
                                                    //        //case 0x00:
                                                    //        //    {
                                                    //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "底板文件正在更新...\r\n";
                                                    //        //    }
                                                    //        //    break;
                                                    //        //case 0x01:
                                                    //        //    {
                                                    //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "底板更新完成,10S后手动重启底板～\r\n";

                        //        //    }
                        //        //    break;
                        //        //case 0x02:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "软体传输异常，即将启动原软体\r\n";
                        //        //    }
                        //        //    break;
                        //        //case 0x03:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "软体更新失败，必须重新更新\r\n";
                        //        //    }
                        //        //    break;
                        //        //case 0x05:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "软体为非法文件，即将启动原软体\r\n";
                        //        //    }
                        //        //    break;
                        //        //case 0x06:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "软体载入成功，正在运行...\r\n";

                        //        //    }
                        //        //    break;
                        //        //case 0x07:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "当前软体工作模式：Normal\r\n";
                        //        //    }
                        //        //    break;
                        //        //case 0x08:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "当前软体工作模式：Debug\r\n";
                        //        //        Setting.TempRecord.VerChecking = true;
                        //        //    }
                        //        //    break;
                        //        //case 0x09:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "BMP写入OK\r\n";
                        //        //    }
                        //        //    break;
                        //        //case 0x0a:
                        //        //    {
                        //        //        textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "CFG写入OK\r\n";
                        //        //    }
                        //        //    break;
                        //        default:
                        //            break;
                        //    }
                        //}

                        //------------------------------------------------------------------------------------------  
                        //else if (Rec_tmp[0] == 0x1D)
                        //{
                        //    switch (Rec_tmp[1])
                        //    {
                        //        case 0x05://2832回读
                        //            {
                        //                // textBox1.Text = Convert.ToString(Rec_tmp[3], 2).PadLeft(8, '0') + " " + Convert.ToString(Rec_tmp[4], 2).PadLeft(8, '0');
                        //                textBox1.Text = Convert.ToString(Rec_tmp[4], 16).PadLeft(2, '0') + Convert.ToString(Rec_tmp[5], 16).PadLeft(2, '0') + " " + Convert.ToString(Rec_tmp[6], 16).PadLeft(2, '0') + Convert.ToString(Rec_tmp[7], 16).PadLeft(2, '0');
                        //            }
                        //            break;
                        //        default:
                        //            break;
                        //    }
                        //}
                        //------------------------------------------------------------------------------------------
                        if (Rec_tmp[0] == 0x96)
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x13:
                                    {
                                        string tmp = "";                    //8bit  read
                                        {
                                            for (int i = 0; i < (Rec_tmp[2] ); i++)
                                            {
                                                //textBox_flash_log.AppendText(tmp + "0x");
                                                if (i == (Rec_tmp[2] ))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i+3]);//16进制
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i+3]) + ",";//16进制
                                                }
                                            }
                                        }
                                        textBox_flash_log.AppendText(tmp + "\r\n");
                                        if (flash_address_get > flash_end)
                                        { textBox_flash_log.AppendText(tmp + "\r\n"); }
                                        //frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "visionox 8bit寄存器--读 OK！\r\n";
                                        Application.DoEvents();
                                    }
                                    break;
                            }
                        }
                        else if (Rec_tmp[0] == 0x99) //GENWR
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "visionox 寄存器\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        {
                                            for (int i = 4; i <= (Rec_tmp[2] + 2); i++)
                                            {
                                                //textBox_flash_log.AppendText(tmp + "0x");
                                                if (i == (Rec_tmp[2] + 2))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]);//16进制
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                                }
                                            }
                                        }
                                        textBox_flash_log.AppendText(tmp + "\r\n");
                                        if (flash_address_get > flash_end)
                                        { textBox_flash_log.AppendText(tmp + "\r\n"); }
                                        //frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "visionox 8bit寄存器--读 OK！\r\n";
                                        Application.DoEvents();
                                    }
                                    break;
                                case 0x03:
                                    {
                                        string tmp = "";
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[3]) + ",";  //16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[4]) + ",";//16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[5]);      //16进制
                                        textBox_flash_log.AppendText(tmp + "\r\n");
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "visionox 16bit寄存器--读 OK！\r\n";
                                        Application.DoEvents();

                                    }
                                    break;
                                case 0x04:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                        {
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "vpp off！\r\n";
                                        }
                                        else if (Rec_tmp[3] == 0x01)
                                        {
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "vpp on！\r\n";
                                        }
                                    }
                                    break;
                            }
                        }



                        //----------------------------------------------------------------------------------------------------  
                        textBox_flash_log.SelectionStart = this.textBox_flash_log.Text.Length;
                        textBox_flash_log.ScrollToCaret();//滚动到光标处
                        //if (textBox_flash_log.Lines.Length > 500) textBox_flash_log.Text = null;

                        frmHelp.textBox1.SelectionStart = this.frmHelp.textBox1.Text.Length;
                        frmHelp.textBox1.ScrollToCaret();//滚动到光标处
                        //if (frmHelp.textBox1.Lines.Length > 500) frmHelp.textBox1.Text = null;

                    }));
                }
            }
            finally
            {
                Listening = false;
            }
        }
        #endregion

        private void Save_Click(object sender, EventArgs e)
        {
            //SaveFileDialog sfd = new SaveFileDialog();
            //sfd.InitialDirectory = @"C:\Users\Desktop";
            //sfd.Title = "请选择要保存的文件路径";
            //sfd.Filter = "文本文件|*.txt|所有文件|*.*";
            //sfd.ShowDialog();

            ////获得用户要保存的文件的路径
            //string path = sfd.FileName;
            //if (path == "")
            //{
            //    return;
            //}
            //using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            //{
            //    //byte[] buffer = Encoding.Default.GetBytes(Main_txtbox.Text);
            //    //byte[] buffer = Encoding.Default.GetBytes(Display_Box.Text);

            //    //fsWrite.Write(buffer, 0, buffer.Length);
            //}
            //MessageBox.Show("保存成功");
        }

        private void btn_erase_Click(object sender, EventArgs e)
        {
            //Reg Page HEX 列 清空
            //AR1.Text = BR1.Text = CR1.Text = DR1.Text = ER1.Text = FR1.Text = GR1.Text = HR1.Text = IR1.Text = JR1.Text = "";
            //AP1.Text = BP1.Text = CP1.Text = DP1.Text = EP1.Text = FP1.Text = GP1.Text = HP1.Text = IP1.Text = JP1.Text = "";
            //AHEX.Text = BHEX.Text = CHEX.Text = DHEX.Text = EHEX.Text = FHEX.Text = GHEX.Text = HHEX.Text = IHEX.Text = JHEX.Text = "";
            //A1.Text = B1.Text = C1.Text = D1.Text = E1.Text = F1.Text = G1.Text = H1.Text = I1.Text = J1.Text = "";
        }
        private static bool DelayMs(int delayTime)
        {
            DateTime current = DateTime.Now;
            while (current.AddMilliseconds(delayTime) > DateTime.Now)
            {
                Application.DoEvents();
            }
            return true;
            //Thread t = new Thread(o => Thread.Sleep(delayTime));
            //t.Start(this);
            //while(t.IsAlive)
            //{
            //    ////防止UI假死
            //    Application.DoEvents();
            //}
            //return true;
            //DateTime now = DateTime.Now;
            //int s;
            //do
            //{
            //    TimeSpan spand = DateTime.Now - now;
            //    s = spand.Milliseconds;
            //    Application.DoEvents();
            //}
            //while (s < delayTime);
            //return true;
        }
        private void Flash_Read_Click(object sender, EventArgs e)
        {
            Byte flash_address_high = 0;
            Byte flash_address_middle = 0;
            Byte flash_address_low = 0;

            Flash_Read.Enabled = false;
            END_ADD_txt_TextChanged(null, null);

            if (flash_end < flash_start)
            {
                MessageBox.Show("flash起始&终止地址计算异常.");
                Flash_Read.Enabled = true;
                return;
            }
            if (IC_FLASH_TYPE == 0)
            {
                MessageBox.Show("IC + flash type请选择.");
                Flash_Read.Enabled = true;
                return;
            }
            for (flash_address_get = flash_start; flash_address_get <= flash_end; flash_address_get++)
            {
                flash_address_high = Convert.ToByte((Convert.ToUInt64(flash_address_get) & 0xFF0000) >> 16);
                flash_address_middle = Convert.ToByte((Convert.ToUInt64(flash_address_get) & 0x00FF00) >> 8);
                flash_address_low = Convert.ToByte((Convert.ToUInt64(flash_address_get) & 0x0000FF) >> 0);


                //Send_buf_code_all(0x99, 0x1c, 0x02, 0xFE, 0x26);
                if ((Send_buf_code(0xFE, 0x26) != FLAG_OK) || (Stop_flag.Enabled == false)) //////check serial port is OK??
                {
                    frmHelp.textBox1.Text = frmHelp.textBox1.Text + "," + "\r\n";
                    Flash_Read.Enabled = true;
                    Stop_flag.Enabled = true;
                    flash_address_get = flash_end;
                    return;
                };
                Send_buf_code(0xF3, 0x02);
                Send_buf_code(0x31, 0x03);
                Send_buf_code(0x15, flash_address_high);/////FLASH[23:16]
                Send_buf_code(0x16, flash_address_middle);/////FLASH[15;8]
                Send_buf_code(0x17, flash_address_low);/////FLASH[7:0]
                Send_buf_code(0x18, 0x00);
                Send_buf_code(0x19, 0x00);
                Send_buf_code(0x1A, 0x20);
                Send_buf_code(0xF2, 0x01);
                /////DELAY
                //DelayMs(1); //Thread.Sleep(200); //1秒=1000毫秒，  delay 200ms
                Send_buf_code(0xFE, 0x26);
                Send_buf_code(0xF3, 0x10);
                ////READ BACK
                //Send_buf_code_all(0x99, 0x24, 0x02, 0xd7, 0x01);
                Read_buf_code(0xd7, 0x01);
                //DelayMs(1);
                //Thread.Sleep(500); //1秒=1000毫秒，  delay 200ms

                progressBar_flash_data.Value = (flash_address_get - flash_start) * 100 / (flash_end - flash_start);
                Application.DoEvents();

                if (frmHelp.Child_Gamma_Window_Open_Enable == true)
                {
                    //MessageBox.Show("IC + flash type请选择.");
                    Flash_Read.Enabled = true;
                    flash_address_get = flash_end;
                    return;
                }
            }
            /*
                FE,26
                f3,02
                31,03
                15,00/////FLASH[23:16]
                16,00////FLASH[15;8]
                17,0b////FLASH[7:0]
                18,00
                19,00
                1A,20
                F2,01
                DELAY200
                FE,26
                F3,10
                IC READ
                D7,01
              */

            Flash_Read.Enabled = true;
            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "\r\n";
        }

        private void END_ADD_txt_TextChanged(object sender, EventArgs e)
        {
            flash_end = Convert.ToInt32(Int32.Parse(END_ADD_txt.Text, System.Globalization.NumberStyles.HexNumber));
            flash_start = Convert.ToInt32(Int32.Parse(Start_ADD_txt.Text, System.Globalization.NumberStyles.HexNumber));
            IC_FLASH_TYPE = Convert.ToInt32(cBx_Item_Set.SelectedIndex) + 1;
        }
        static byte[] GetCRCArray(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        public UInt16 Send_buf_code(UInt16 addr, UInt16 datar)
        {
            byte[] Send_Datax = new byte[7];
            Setting.TempRecord.cmdLen = 3 + 2 + 2;///index=3;  length=2 or N;  crc=2;

            Send_Datax[0] = 0x99; //GenWR-->0x99;  GenWRHFZ-->0x9F;  GenSTM32FSMC2FPGA-->0x9D;  PMU_MTR-->0x9E;  BMP_FLAG-->0xBD;
            Send_Datax[1] = 0x14;//195  0x10-->write;0x20-->read;
            Send_Datax[2] = 0x02; //length

            //Send_buf[3] = Convert.ToByte(addr >> 8);
            //Send_buf[4] = Convert.ToByte(datar >> 8);
            Send_Datax[3] = Convert.ToByte(addr & 0xff);
            Send_Datax[4] = Convert.ToByte(datar & 0xff);

            CRCData.CalculateCrc16(Send_buf, out Send_Datax[5], out Send_Datax[6]);
            try
            {
                frmHelp.comPort.Write(Send_Datax, 0, 7);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                //Send_Datax;
                return ERROR_0;
            }
            return FLAG_OK;
        }

        private void Send_buf_code_all(UInt16 index_header, UInt16 index_type, UInt16 index_length, UInt16 addr, UInt16 datar)
        {

            Setting.TempRecord.cmdLen = 3 + (index_length & 0xFF) + 2;///index=3;  length=2 or N;  crc=2;
            Send_buf = new byte[Setting.TempRecord.cmdLen];
            Send_buf[0] = Convert.ToByte(index_header & 0xff); //GenWR-->0x99;  GenWRHFZ-->0x9F;  GenSTM32FSMC2FPGA-->0x9D;  PMU_MTR-->0x9E;  BMP_FLAG-->0xBD;
            Send_buf[1] = Convert.ToByte(index_type & 0xff);//195  0x10-->write;0x20-->read;
            Send_buf[2] = Convert.ToByte(index_length & 0xff); //length

            //Send_buf[3] = Convert.ToByte(addr >> 8);
            //Send_buf[4] = Convert.ToByte(datar >> 8);
            Send_buf[3] = Convert.ToByte(addr & 0xff);
            Send_buf[4] = Convert.ToByte(datar & 0xff);

            CRCData.CalculateCrc16(Send_buf, out Send_buf[5], out Send_buf[6]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 7);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }

        private void Read_buf_code(UInt16 addr, UInt16 datar)
        {
            Send_buf = new byte[7];
            Setting.TempRecord.cmdLen = 3 + 2 + 2;///index=3;  length=2 or N;  crc=2;

            Send_buf[0] = 0x99; //GenWR-->0x99;  GenWRHFZ-->0x9F;  GenSTM32FSMC2FPGA-->0x9D;  PMU_MTR-->0x9E;  BMP_FLAG-->0xBD;
            Send_buf[1] = 0x20;//195  0x10-->write;0x20-->read;
            Send_buf[2] = 0x02; //length

            //Send_buf[3] = Convert.ToByte(addr >> 8);
            //Send_buf[4] = Convert.ToByte(datar >> 8);
            Send_buf[3] = Convert.ToByte(addr & 0xff);
            Send_buf[4] = Convert.ToByte(datar & 0xff);

            CRCData.CalculateCrc16(Send_buf, out Send_buf[5], out Send_buf[6]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 7);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }

        private void Stop_flag_Click(object sender, EventArgs e)
        {
            Stop_flag.Enabled = false;
        }

        private void OLED_LOGIC(byte LOGIC_TYPE)
        {
            Send_buf = new byte[25];
            //Button btnTmp = (Button)sender;
            Setting.TempRecord.cmdLen = 25;
            Send_buf[0] = 0x0A; //LCD配置标志
            Send_buf[2] = 0x15; //数据长度
            Send_buf[1] = 0x17; //////LCD index
            Send_buf[6] = LOGIC_TYPE;///定制逻辑图编号 目前40张定制图片

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }

        private void CommandModeSelectFlagValue(Byte index_command)
        {
            switch (index_command)
            {
                case 0x05:
                    MipiCommandModeSelect_Flag = 0x05;
                    break;

                case 0x15:
                    MipiCommandModeSelect_Flag = 0x15;
                    break;

                case 0x29:
                    MipiCommandModeSelect_Flag = 0x29;
                    break;

                case 0x39:
                    MipiCommandModeSelect_Flag = 0x39;
                    break;

                default:
                    MipiCommandModeSelect_Flag = 0x04;
                    break;
            }
            MipiCommandModeSelect_Flag = 0x04;
        }

        private void Flash_Generate_File_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            byte codes_count = 0;
            string strLine = Convert.ToString(textBox_flash_write.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组
            bool Transmit_info_flag = true;

            switch (btnTmp.Name)
            {
                case "LOAD":
                    {
                        OpenFileDialog of = new OpenFileDialog();
                        of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                        of.Title = "MIPI DDIC Reg Write";

                        if (of.ShowDialog() == DialogResult.OK)
                        {
                            textBox_flash_write.Clear();
                            //读取文本信息
                            FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                            StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                            string str_generate = streamReader.ReadLine();
                            //循环读取文本信息
                            while (str_generate != null)
                            {
                                textBox_flash_write.AppendText(str_generate + "\r\n");
                                str_generate = streamReader.ReadLine(); //循环读取下一行
                            }
                            fs.Close(); //关闭流
                            streamReader.Close();
                        }
                    }
                    break;

                case "SAVE":
                    {
                        if (textBox_flash_write.Text == string.Empty)
                        {
                            MessageBox.Show("内容为空!");
                        }
                        else
                        {
                            //创建保存对话框对象
                            SaveFileDialog save = new SaveFileDialog();
                            save.Filter = "Code files (*.txt)|*.txt"; //过滤文件类型
                            save.FilterIndex = 1;
                            save.RestoreDirectory = true;
                            if (save.ShowDialog() == DialogResult.OK)
                            {
                                string path = save.FileName;
                                save.DefaultExt = ".txt";
                                StreamWriter sw = new StreamWriter(path);
                                sw.WriteLine(textBox_flash_write.Text);
                                sw.Close();
                            }
                        }
                    }
                    break;

                case "Flash_Write":
                    {
                        string[] per_arr = null;
                        int Byte_n = 0;
                        try
                        {
                            Flash_Write.Enabled = false;
                            //Send_buf[0] = 0x99
                            //Send_buf[1] = 读写区分
                            //Send_buf[2] = 长包短包-Generate&DCS
                            //Send_buf[3] = 初始化数据包长含指令
                            string str_test = string.Empty;
                            string perline = string.Empty;

                            byte POWER_Sequence = 0x30, READ_flag = 0x20, WRITE_flag = 0x10, target_cmd = 0;
                            byte READ_16bit_flag = 0x40, READ_8bit_flag = 0x00;
                            byte wr_flag = 0x10, end_flag = 0x80, read_tmp0 = 0, Cmd_transmit_flag = 0;
                            int i = 0, temp = 0;
                            int rewrite_start = 0, rewrite_end = 0, reread_start = 0, reread_end = 0;
                            byte Rerun_times = 0;
                            bool Re_write_run_flag = false, Re_read_run_flag = false; ;
                            bool operate_pmu_only = false;
                            //  byte pmu_operate = 0xff;
                            // int pmu_value = 0;
                            //Setting.TempRecord.cmdLen = arr.Length + 5;
                            //Send_buf = new byte[arr.Length + 5];
                            Send_buf = new byte[1];
                            if (textBox_flash_write.Text == string.Empty)
                            {
                                MessageBox.Show("内容为空!");
                            }
                            else
                            {
                                textBox_flash_log.AppendText("\r\n");
                                arr = strLine.Split('\n'); //以逗号分割，添加到数
                                for (i = 0; i < arr.Length; i++)  //获取的行数
                                {
                                    progressBar_flash_data.Value = Convert.ToInt32((double)i / (arr.Length) * 100);
                                    //GenWR_lab_text.Text = progressBar_flash_data.Value.ToString() + "%";
                                    Application.DoEvents();

                                    per_arr = null;
                                    perline = arr[i];
                                    perline = perline.Replace("SPI_8bit(", "");
                                    perline = perline.Replace("SPI_16bit(", "");
                                    perline = perline.Replace("SPI_16bit_R(", "");
                                    perline = perline.Replace("SPI_32bit(", "");
                                    perline = perline.Replace("IIC_xxbit(", ""); 
                                    perline = perline.Replace("IIC_xxbit_read(", "");
                                    perline = perline.Replace("IIC_16bit(", "");
                                    perline = perline.Replace("IIC_16bit_R(", "");
                                    perline = perline.Replace("REGS.WRITE(", "");
                                    perline = perline.Replace("mipi(", "");
                                    perline = perline.Replace("PIC(", "");
                                    perline = perline.Replace("PIC_logic(", "");
                                    perline = perline.Replace(")", "");
                                    perline = perline.Replace(";", "");
                                    perline = perline.Replace("0x", "");
                                    perline = perline.Replace("REGW", "");
                                    perline = perline.Replace("delay", "DELAY");// 
                                    perline = perline.Replace("Delay", "DELAY");// 
                                    perline = perline.Replace("-", ",");
                                    perline = perline.Replace(" ", "");
                                    perline = perline.Replace("[", "");
                                    perline = perline.Replace("]", "");
                                    perline = perline.Replace("*/", "GO");
                                    perline = perline.Replace("/*", "PULSE");
                                    perline = perline.Replace("\\", "/");
                                    perline = perline.Replace("#", "/");
                                    perline = perline.Replace("//", "/");
                                    perline = perline.Replace("\t", "/");
                                    perline = perline.Replace("\r", "/");
                                    perline = perline.Replace("\n", "/"); //单行整体处理.  

                                    if (perline.Contains("/")) //去掉注解
                                    {
                                        perline = perline.Substring(0, perline.IndexOf("/"));
                                    }
                                    perline = perline.ToUpper();


                                    //--------------------------------------------------------------------------------------
                                    if (Re_write_run_flag == true)//the Rewrite function turned on
                                    {
                                        perline = perline.Replace("}", "");
                                        perline = perline.Replace("{", "");
                                        if (i == rewrite_end)
                                        {
                                            if (temp < Rerun_times)
                                            {
                                                i = rewrite_start; //return to start site "{"所在行
                                                temp = temp + 1;
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "REWRITE times: " + temp.ToString() + "!\r\n";
                                            }
                                            else
                                            {
                                                i = rewrite_end; // "}"所在行 mark end site                                                  
                                                Rerun_times = 0; temp = 0;
                                                Re_write_run_flag = false;// times over,function off
                                                rewrite_start = 0;
                                                rewrite_end = 0;
                                            }
                                        }
                                        else
                                        {
                                            ;
                                        }
                                    }
                                    else if (Re_read_run_flag == true)//the Reread function turned on
                                    {
                                        perline = perline.Replace("}", "");
                                        perline = perline.Replace("{", "");
                                        if (i == reread_end)
                                        {
                                            if (temp < Rerun_times)
                                            {
                                                i = reread_start; //return to start site "{"所在行
                                                temp = temp + 1;
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "REREAD times: " + temp.ToString() + "!\r\n";
                                            }
                                            else
                                            {
                                                i = reread_end; // "}"所在行 mark end site                                                  
                                                Rerun_times = 0; temp = 0;
                                                Re_read_run_flag = false;// times over,function off
                                                reread_start = 0;
                                                reread_end = 0;
                                            }
                                        }
                                        else
                                        {
                                            ;
                                        }
                                    }
                                    //--------------------------------------------------------------------------------------

                                    codes_count = 0;
                                    per_arr = perline.Split(','); //以逗号分割，添加到数组     
                                    int mode_send_buff = 0;//////设定需要开传输数据量的参数
                                    if ((arr[i].Contains("SPI_16bit(")) || (arr[i].Contains("SPI_16bit_R(")) || (arr[i].Contains("IIC_16bit(")) || (arr[i].Contains("IIC_16bit_R(")))
                                    {
                                        mode_send_buff = 1;
                                        Send_buf = new byte[per_arr.Length + 5 + mode_send_buff];//统计“，”的个数，
                                        Setting.TempRecord.cmdLen = per_arr.Length + 5 + mode_send_buff;
                                    }
                                    else if (arr[i].Contains("SPI_32bit("))
                                    {
                                        mode_send_buff = 3;
                                        Send_buf = new byte[per_arr.Length + 5 + mode_send_buff];//统计“，”的个数，
                                        Setting.TempRecord.cmdLen = per_arr.Length + 5 + mode_send_buff;
                                    }
                                    else if ((arr[i].Contains("IIC_xxbit("))||(arr[i].Contains("IIC_xxbit_read(")))
                                    {
                                        //mode_send_buff = Convert.ToByte(per_arr[0], 16);
                                        mode_send_buff = 0;
                                        Send_buf = new byte[per_arr.Length + 5 + mode_send_buff];//统计“，”的个数，
                                        Setting.TempRecord.cmdLen = per_arr.Length + 5 + mode_send_buff;
                                    }
                                    else
                                    {
                                        mode_send_buff = 0;
                                        Send_buf = new byte[per_arr.Length + 5 + mode_send_buff - 1];//统计“，”的个数，
                                        Setting.TempRecord.cmdLen = per_arr.Length + 5 + mode_send_buff - 1;
                                    }
                                    DelayMs(1);
                                    
                                    if (mode_send_buff == 0)
                                    {
                                       
                                    }

                                    for (Byte_n = 0; Byte_n < per_arr.Length; Byte_n++)   //逐个处理
                                    {
                                        // Application.DoEvents();
                                        if (arr[i].Contains("mipi("))
                                        {
                                            wr_flag = WRITE_flag;
                                            Send_buf[0] = 0x96;//通用读写
                                            if ((per_arr[0] != string.Empty) && (Byte_n == 0))
                                            {
                                                CommandModeSelectFlagValue(Convert.ToByte(per_arr[0], 16));
                                                //codes_count++;
                                            }
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                //  foreach (char ch in per_arr[n]) //收集data的位置
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 2] = Convert.ToByte(per_arr[Byte_n], 16);
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                                //textBox_flash_log.Text +=  Convert.ToString(Send_buf[n + 3]) + ",";

                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 2]) + ",");
                                            }
                                        }
                                        else if (arr[i].Contains("REGS.WRITE("))
                                        {
                                            wr_flag = WRITE_flag;
                                            Send_buf[0] = 0x96;//通用读写
                                            if ((per_arr[1] != string.Empty) && (Byte_n == 1))
                                            {
                                                CommandModeSelectFlagValue(Convert.ToByte(per_arr[0], 16));
                                                codes_count++;
                                            }
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                //  foreach (char ch in per_arr[n]) //收集data的位置
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = Convert.ToByte(per_arr[Byte_n], 16);
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                                //textBox_flash_log.Text +=  Convert.ToString(Send_buf[n + 3]) + ",";

                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                            }
                                        }
                                        else if (arr[i].Contains("SPI_8bit("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x02;
                                            Send_buf[0] = 0x96;//通用读写
                                            if (per_arr[Byte_n] != string.Empty)
                                            {
                                                //  foreach (char ch in per_arr[n]) //收集data的位置
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = Convert.ToByte(per_arr[Byte_n], 16);
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                                //textBox_flash_log.Text +=  Convert.ToString(Send_buf[n + 3]) + ",";

                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                            }
                                        }
                                        else if (arr[i].Contains("SPI_16bit("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x02;
                                            //Send_buf[0] = 0x0D;//通用读写
                                            Send_buf[0] = 0x96;//通用读写

                                            //   Application.DoEvents();

                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                                //    textBox_flash_log.AppendText(String.Format("{0:X2}", Byte_n) + ",");
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                            }
                                            //   Application.DoEvents();
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                //target_cmd = Send_buf[3];
                                                //    textBox_flash_log.AppendText(String.Format("{0:X2}", Byte_n) + ",");
                                                //    textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[n + 3]) + ",");
                                                codes_count += 2;
                                                //    textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[n + 4]) + ",");
                                                if (frmHelp.Dis_mode.SelectedIndex == 1)
                                                {
                                                    //       Send_buf[n + 3] = byte.Parse((Convert.ToInt32(per_arr[n].Substring(0, 2), 16)).ToString());
                                                    //       Send_buf[n + 4] = byte.Parse((Convert.ToInt32(per_arr[n].Substring(2, 2), 16)).ToString());
                                                    //       target_cmd = Send_buf[3];
                                                    //codes_count += 2;
                                                    textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                                    textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 4]) + ",");
                                                }
                                                Byte_n = 3;
                                                //   textBox_flash_log.AppendText(String.Format("{0:X2}", Byte_n) + ",");
                                            }
                                            //   textBox_flash_log.AppendText(String.Format("{0:X2}", Byte_n) + ",");
                                            if (Byte_n > 3)
                                            { Byte_n = 3; }
                                        }
                                        else if (arr[i].Contains("SPI_16bit_R("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x12;
                                            //Send_buf[0] = 0x0D;//通用读写
                                            Send_buf[0] = 0x96;//通用读写
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                            }
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count += 2;
                                                if (frmHelp.Dis_mode.SelectedIndex == 1)
                                                {
                                                    Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                    Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                    target_cmd = Send_buf[3];
                                                    //codes_count += 2;
                                                    //   textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[n + 3]) + ",");
                                                    //    textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[n + 4]) + ",");
                                                }
                                                Byte_n = 3;
                                            }
                                        }
                                        else if (arr[i].Contains("SPI_32bit("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x06;
                                            //Send_buf[0] = 0x0D;//通用读写
                                            Send_buf[0] = 0x96;//通用读写
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count++;

                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                            }
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                Send_buf[Byte_n + 6] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(4, 2), 16)).ToString());
                                                Send_buf[Byte_n + 5] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(6, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count += 4;
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 4]) + ",");
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 6]) + ",");
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 5]) + ",");
                                            }
                                            Byte_n = 6;
                                        }
                                        else if (arr[i].Contains("IIC_16bit("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x02;
                                            Send_buf[0] = 0x96;//通用读写
                                            ////处理指令头，第一个byte  IIC——address
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                            }
                                            ////处理2byte数据，IIC ---16bit  data
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                codes_count += 2;
                                                if (frmHelp.Dis_mode.SelectedIndex == 1)
                                                {
                                                    textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                                    textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 4]) + ",");
                                                }
                                                Byte_n = 3;
                                            }
                                        }
                                        else if (arr[i].Contains("IIC_xxbit("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x02;
                                            Send_buf[0] = 0x96;//通用读写
                                            ////处理指令头，第一个byte  IIC——address
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                            }
                                            
                                            ////处理2byte数据，IIC ---16bit  data
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                operate_pmu_only = false;
                                                int ii_temp = 0;
                                                for (ii_temp = 0; ii_temp < Convert.ToByte(per_arr[0], 16); ii_temp++)
                                                {
                                                    Send_buf[Byte_n + 3+ii_temp] = byte.Parse((Convert.ToInt32(per_arr[Byte_n + ii_temp].Substring(0, 2), 16)).ToString());
                                                    codes_count ++;
                                                    
                                                }
                                                //Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                //Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                //codes_count += 2;
                                                if (frmHelp.Dis_mode.SelectedIndex == 1)
                                                {
                                                    for (ii_temp = 0; ii_temp < Convert.ToByte(per_arr[0], 16); ii_temp++)
                                                    {
                                                        //Send_buf[Byte_n + 3 + ii_temp] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0 + 2 * ii_temp, 2), 16)).ToString());
                                                        textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3 + ii_temp]) + ",");
                                                        //codes_count++;
                                                    }
                                                    //textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                                    //textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 4]) + ",");
                                                }
                                                Byte_n = 1+ Convert.ToByte(per_arr[0], 16);
                                            }
                                        }
                                        else if (arr[i].Contains("IIC_xxbit_read("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x12;
                                            Send_buf[0] = 0x96;//通用读写
                                            ////处理指令头，第一个byte  IIC——address
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                                textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                            }

                                            ////处理2byte数据，IIC ---16bit  data
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                operate_pmu_only = false;
                                                int ii_temp = 0;
                                                for (ii_temp = 0; ii_temp < Convert.ToByte(per_arr[0], 16); ii_temp++)
                                                {
                                                    Send_buf[Byte_n + 3 + ii_temp] = byte.Parse((Convert.ToInt32(per_arr[Byte_n + ii_temp].Substring(0, 2), 16)).ToString());
                                                    codes_count++;

                                                }
                                                //Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                //Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                //codes_count += 2;
                                                if (frmHelp.Dis_mode.SelectedIndex == 1)
                                                {
                                                    for (ii_temp = 0; ii_temp < Convert.ToByte(per_arr[0], 16); ii_temp++)
                                                    {
                                                        //Send_buf[Byte_n + 3 + ii_temp] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0 + 2 * ii_temp, 2), 16)).ToString());
                                                        textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3 + ii_temp]) + ",");
                                                        //codes_count++;
                                                    }
                                                    //textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 3]) + ",");
                                                    //textBox_flash_log.AppendText(String.Format("{0:X2}", Send_buf[Byte_n + 4]) + ",");
                                                }
                                                Byte_n = 1 + Convert.ToByte(per_arr[0], 16);
                                            }
                                        }
                                        else if (arr[i].Contains("IIC_16bit_R("))
                                        {
                                            wr_flag = WRITE_flag;
                                            MipiCommandModeSelect_Flag = 0x12;
                                            Send_buf[0] = 0x96;//通用读写
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count++;
                                            }
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n != 0))
                                            {
                                                operate_pmu_only = false;
                                                Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                target_cmd = Send_buf[3];
                                                codes_count += 2;
                                                if (frmHelp.Dis_mode.SelectedIndex == 1)
                                                {
                                                    Send_buf[Byte_n + 3] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                                                    Send_buf[Byte_n + 4] = byte.Parse((Convert.ToInt32(per_arr[Byte_n].Substring(2, 2), 16)).ToString());
                                                    target_cmd = Send_buf[3];
                                                }
                                                Byte_n = 3;
                                            }
                                        }
                                        else if (arr[i].Contains("PIC("))
                                        {
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                /// </OLED逻辑狗>
                                                /// <param 0  name="LOGIC_TYPE"></图类型>
                                                /// <param 1  name="M_R"></底色-红通道>
                                                /// <param 2  name="M_G"></底色-绿通道>
                                                /// <param 3  name="M_B"></底色-蓝通道>
                                                /// <param 4  name="L_R"></局部-色红通道>
                                                /// <param 5  name="L_G"></局部-色红通道>
                                                /// <param 6  name="L_B"></局部-色红通道>
                                                /// <param 7  name="X0"></局部-水平方向起点坐标>
                                                /// <param 8  name="X1"></局部-水平方向终点坐标>
                                                /// <param 9  name="Y0"></局部-竖直方向终点坐标>
                                                /// <param 10 name="Y1"></局部-竖直方向终点坐标>
                                                /// <param 11 name="R0"></局部-半径>
                                                ////////////////////////byte LOGIC_TYPE,                byte M_R,                         byte M_G,                     byte M_B,                 byte L_R,                  byte L_G,                  byte L_B,                        UInt16 X0,                     UInt16 X1,                 UInt16 Y0,                  UInt16 Y1,                        UInt16 R0
                                                frmHelp.OLED_LOGIC_G0(Convert.ToByte(per_arr[0]), Convert.ToByte(per_arr[1]), Convert.ToByte(per_arr[2]), Convert.ToByte(per_arr[3]), Convert.ToByte(per_arr[4]), Convert.ToByte(per_arr[5]), Convert.ToByte(per_arr[6]), Convert.ToUInt16(per_arr[7]), Convert.ToUInt16(per_arr[8]), Convert.ToUInt16(per_arr[9]), Convert.ToUInt16(per_arr[10]), Convert.ToUInt16(per_arr[11]));
                                                Byte_n = 12;
                                            }
                                        }
                                        else if (arr[i].Contains("PIC_logic("))
                                        {
                                            if ((per_arr[Byte_n] != string.Empty) && (Byte_n == 0))
                                            {
                                                OLED_LOGIC(Convert.ToByte(per_arr[0]));
                                                Byte_n = 1;
                                            }
                                        }
                                        else if (per_arr[Byte_n].Contains("DELAY"))
                                        {
                                            string gen_delay = per_arr[Byte_n].Replace("DELAY", "");
                                            DelayMs(Convert.ToInt16(gen_delay));
                                        }
                                        else
                                        {
                                            ;
                                        }

                                        if (Stop_flag.Enabled == false)
                                        {
                                            i = arr.Length;
                                            Flash_Write.Enabled = true;
                                            Stop_flag.Enabled = true;
                                            return;
                                        }
                                        Thread.Sleep(3);
                                        // textBox_flash_log.AppendText(String.Format("{0:X2}", Byte_n) + ",");
                                    }//发送单条指令
                                    if (codes_count > 0)
                                    {
                                        if (Transmit_info_flag == true)
                                        {
                                            if (wr_flag == WRITE_flag)//write
                                            {
                                                Send_buf[2] = (byte)(codes_count);
                                                Send_buf[1] = (byte)(MipiCommandModeSelect_Flag);
                                            }

                                            {
                                                CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
                                            }
                                            textBox_flash_log.AppendText("\r\n");
                                            try
                                            {
                                                {
                                                    frmHelp.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);
                                                }
                                                if (wr_flag == READ_flag)
                                                {
                                                    //Thread.Sleep(50 + 10 * read_tmp0);
                                                }
                                                else if (wr_flag == WRITE_flag)
                                                {
                                                    //Thread.Sleep(15);
                                                }
                                                Thread.Sleep(15);
                                            }
                                            catch
                                            {
                                                MessageBox.Show("串口有误，请检查", "错误");
                                                Flash_Write.Enabled = true;
                                                return;
                                            }
                                        }
                                    }
                                }
                                //if ((wr_flag == WRITE_flag) && (operate_pmu_only == false)) //写结束标志 LP00- transmit -HS
                                //{
                                //    //--------------------------------最后一笔--------------------------------------------------
                                //    Transmit_info_flag = true;
                                //    Setting.TempRecord.cmdLen = 7;
                                //    Send_buf = new byte[7];
                                //    Send_buf[0] = 0x99;//通用读写
                                //    Send_buf[1] = (byte)(end_flag | wr_flag);
                                //    Send_buf[2] = 2;
                                //    CRCData.CalculateCrc16(Send_buf, out Send_buf[5], out Send_buf[6]);
                                //    try
                                //    {
                                //        frmHelp.comPort.Write(Send_buf, 0, 7);
                                //        Thread.Sleep(100);
                                //    }
                                //    catch
                                //    {
                                //        MessageBox.Show("串口有误，请检查", "错误");
                                //    }
                                //}
                                //else if (operate_pmu_only == true)
                                //{
                                //    frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "external vpp openning!\r\n";
                                //}
                                progressBar_flash_data.Value = 100;
                            }
                        }
                        catch
                        {
                            string str_log_error = "";
                            str_log_error = (Convert.ToInt32(Byte_n).ToString());
                            //str_log_error = ((Convert.ToInt32(per_arr[Byte_n].Substring(0, 2), 16)).ToString());
                            MessageBox.Show("输入格式不规范!!", "错误");
                            MessageBox.Show("Byte_n =" + str_log_error, "错误");
                            str_log_error = (Convert.ToInt32(per_arr.Length).ToString());
                            MessageBox.Show("per_arr.Length =" + str_log_error, "错误");
                        }
                        Flash_Write.Enabled = true;
                    }
                    break;

                default: break;
            }

        }

        private void textBox_flash_write_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            textBox_flash_write.Clear();
        }

        private void textBox_flash_log_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            textBox_flash_log.Clear();
        }
    }
}